#define _CRT_SECURE_NO_WARNINGS 1

class Solution {
public:
    void flatten(TreeNode* root)
    {
        TreeNode* cur = root;
        while (cur != nullptr)
        {
            TreeNode* Next = cur->left;
            if (cur->left != nullptr)
            {
                TreeNode* pre = cur->left;
                while (pre->right != nullptr)
                {
                    pre = pre->right;
                }
                pre->right = cur->right;
                cur->left = nullptr;
                cur->right = Next;
            }
            cur = cur->right;
        }
    }
};

class Solution {
public:
    void flatten(TreeNode* root)
    {
        if (root == nullptr)
            return;
        stack<TreeNode*> s;
        s.push(root);
        TreeNode* prev = nullptr;
        while (!s.empty())
        {
            TreeNode* cur = s.top();
            s.pop();
            if (prev != nullptr)
            {
                prev->left = nullptr;
                prev->right = cur;
            }
            if (cur->right != nullptr)
                s.push(cur->right);
            if (cur->left != nullptr)
                s.push(cur->left);
            prev = cur;
        }
    }
};

